package com.netty.handler;

import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.pool.AbstractChannelPoolHandler;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.ssl.util.InsecureTrustManagerFactory;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.concurrent.TimeUnit;
/**
 * 默认channelpool消息配置handler
 * @author hmm
 *
 */
public class DefaultChannelPoolHandler extends AbstractChannelPoolHandler {

	public static final String MESSAGE_HANDLER = "messageHandler";
	
	private boolean ssl = false;
	private boolean http = false;
	private boolean heartbeat = false;

	public DefaultChannelPoolHandler(){
		this(false, false);
	}
	
	/**
	 * @param ssl	是否支持https
	 * @param http	是否支持http
	 * 如果两个都为false，则以原始数据方式发送
	 */
	public DefaultChannelPoolHandler(boolean ssl, boolean http){
		this(ssl, http, false);
	}
	/**
	 * 
	 * @param ssl		是否支持https
	 * @param http		是否支持http
	 * @param heartbeat	是否支持心跳检测  间隔时间为秒
	 */
	public DefaultChannelPoolHandler(boolean ssl, boolean http, boolean heartbeat){
		this.http = http;
		this.ssl = ssl;
		this.heartbeat = heartbeat;
	}
	
	@Override
	public void channelAcquired(Channel channel) throws Exception {
		System.out.println("acquired a channel from pool"+channel);
	}

	@Override
	public void channelCreated(Channel channel) throws Exception {
		System.out.println("created a channel from pool"+channel);
		ChannelPipeline pipeline = channel.pipeline();
		if(heartbeat){
			pipeline.addLast(new IdleStateHandler(10, 10, 20, TimeUnit.SECONDS));
		}
		if(ssl){
			SslContext clientContext =  SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();
	        pipeline.addLast("ssl", new SslHandler(clientContext.newEngine(ByteBufAllocator.DEFAULT)));
		}
		if(http || ssl){
			pipeline.addLast("http-codec", new HttpClientCodec(1024, 1024, 8192, false));
		}else{
			pipeline.addLast("frame-decoder", new LineBasedFrameDecoder(1024));
			pipeline.addLast("decoder", new StringDecoder());
			pipeline.addLast("encoder", new StringEncoder());
		}
		pipeline.addLast(MESSAGE_HANDLER, new ClientMessageHandler());
	}

	@Override
	public void channelReleased(Channel channel) throws Exception {
		System.out.println("released a channel "+channel);
	}

}
